//
//  CXLEmoticonManager.swift
//  Emotion
//
//  Created by 曹晓龙 on 15/10/23.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit

/// 管理所有图片表情文件夹
class CXLEmoticonManager: NSObject {

    //MARK: -单例
    static let shareEmoticionManager:CXLEmoticonManager = CXLEmoticonManager()
    
    
    func addFavouriteEmoticon(em:CXLEmoticon){
        
        em.times++
        
        if !emoticonGroups[0].emoticons.contains(em){
            
            emoticonGroups[0].emoticons.insert(em, atIndex: 0)
            
            emoticonGroups[0].emoticons.removeAtIndex(emoticonGroups[0].emoticons.count - 2)
        }
        
        
        emoticonGroups[0].emoticons.sortInPlace { (em1, em2) -> Bool in
             em1.times > em2.times
        }
        
    }
    
    
    /// 存放所有的表情图片模型的数组
    lazy var emoticonGroups = [CXLEmoticonGroup]()
    
    
    // MARK: -构造函数
    private override init() {
        
        super.init()
        
        emoticonGroups.append(CXLEmoticonGroup(dict: ["group_name_cn":"常用A"]))
        
        if let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle"){
            
            let dict = NSDictionary(contentsOfFile: path)!
            
            let array = ((dict["packages"] as! NSArray).valueForKey("id")) as! [String]
            
            for id in array {
            
                getEmoticonGroup(id)
                
            }
        }
    }
    ///  添加图片表情模型
    ///
    ///  - parameter id: 文件夹名
    private func getEmoticonGroup(id:String){
        
        if let path = NSBundle.mainBundle().pathForResource("info.plist", ofType: nil, inDirectory: "Emoticons.bundle/\(id)"){
            
            guard let dict = NSDictionary(contentsOfFile: path) else{
                
                return
            }
            
            emoticonGroups.append(CXLEmoticonGroup(dict: dict as! [String : AnyObject]))
        }
    }
    
    ///  将带表情的[]字符串转换成属性字符串
    func emticonText(str:String, font:UIFont) -> NSAttributedString{
        
        
        let strM = NSMutableAttributedString(string: str)
        
        let pattern = "\\[.*?\\]"
        
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        let result = regex.matchesInString(str, options: [], range: NSRange(location: 0, length:str.characters.count))
        
        var count = result.count
        
        while count > 0{
            
            let range = result[--count].rangeAtIndex(0)
            
            let text = (str as NSString).substringWithRange(range)
            
            if let emoticon = emoticonWithString(text) {
                
                let attribute = CXLEmoticonAttachment(emoticon: emoticon).getImageText(font)
                
                strM.replaceCharactersInRange(range, withAttributedString: attribute)
            }
            
        }
        
        
        return strM.copy() as! NSAttributedString
    }
    ///  从表情包中查询字符串对应的模型
    private func emoticonWithString(string:String) -> CXLEmoticon?{
        
        for p in CXLEmoticonManager.shareEmoticionManager.emoticonGroups{
            
            let emoticon = p.emoticons.filter({ $0.chs == string }).last
            
            
            if emoticon != nil {
                return emoticon!
            }
        }
        
        return nil
    }

    
}
